package com.woniu.smart.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.smart.util.RedisCache;
import com.woniu.smart.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core .Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description: TODO
 * @Author: WangHeng
 * @Date: 2022/10/27 09:06
 */
@Component
public class JWTLogoutSuccessHandler implements LogoutSuccessHandler {
    @Autowired
    private RedisCache redisCache;
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //删除redis中的token信息
        redisCache.deleteObject("rbac"+loginUser.getUsername());
        response.setContentType("application/json;charset=UTF-8");
        String string = new ObjectMapper().writeValueAsString(Result.ok("退出成功"));
        response.getWriter().println(string);
    }
}
